package com.springsummer.information.green.webmvc;

import org.apache.catalina.Context;
import org.apache.catalina.Wrapper;
import org.apache.catalina.servlets.DefaultServlet;
import org.apache.catalina.startup.ContextConfig;
import org.apache.catalina.startup.Tomcat;
import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler;

import java.util.logging.Level;
import java.util.logging.Logger;

public class TomcatStartService {

    private static Logger logger = Logger.getLogger(TomcatStartService.class.getName());

    // main（）应用启动入口
    public static void main(String[] args) throws Exception {
        //访问地址 http://localhost:8080/student/add?name=pingping&age=18&phone=123456789
        //http://localhost:8080/student/studentViewPage?name=pingping&age=18&phone=123456789
        //http://localhost:8080/emp/list?name=pingping&age=18&phone=123456789
        //http://localhost:8080/emp/empViewPage?name=pingping&age=18&phone=123456789

        DefaultServletHttpRequestHandler defaultServletHttpRequestHandler;

        //The default resource-serving servlet for most web applications, used to serve static resources such as HTML pages and images.
        DefaultServlet defaultServlet;

        //启动tomcat https://www.cnblogs.com/lihw-study/p/17281721.html
        //wiki2 Embedded tomcat怎么使用 https://yb.tencent.com/s/8x30xFyBpKsA

        // 1. 实例化 Tomcat 示例（ tomcat 最小启动，Tomcat 类用于嵌入了 tomcat 的应用)
        Tomcat tomcat = new Tomcat();
        // 2. 配置应用上下文
        Context appContext=configContext(tomcat);
        // 2. 配置 Servlet
        configServlet(tomcat,appContext);
        // 3. 启动 tomcat 服务
        tomcat.start();
        logAfterStart(tomcat);
        // 4. 同步等待关闭窗口命令关闭
        tomcat.getServer().await();



    }

    /**
     * 配置 context
     * @param tomcat
     */
    private static Context configContext(Tomcat tomcat) throws Exception {
        // 添加应用上下文配置，并制定 webapp 目录为：/D:/***/embedded-web-container/target/classes/
        String webAppPath = TomcatStartService.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
        logger.info("WebappContextPath:"+webAppPath);


        Context appContext =  tomcat.addContext("/", webAppPath);
        // 必须添加 ContextConfig ，否则 SPI 无法加载 WsSci
        appContext.addLifecycleListener(new ContextConfig());

        return appContext;
    }

    private static void configServlet(Tomcat server,Context context){
        /*
          1. 在应用上下文 "/" 下添加默认 Servlet,映射 url： /
          注意：必须配置 DefaultServlet, webcoket 的 url 依赖。
         */
        //Wrapper defaultServletWrapper = server.addServlet("/", "default", DefaultServlet.class.getTypeName());
        //defaultServletWrapper.addMapping("/");
        // 2. 在应用上下文 "/" 下配置 Welcome Servlet,映射 url： /index

        String servletName="minisMVC";

        Wrapper dispatchServletwrapper = server.addServlet("/", servletName, DispatchServlet.class.getTypeName());
        //welcomeServletwrapper.addMapping("/index");

        //context.addServletMappingDecoded("/hello", "MyServlet");
        context.addServletMappingDecoded("/", servletName);

        //.. and a servlet mapping that maps only /static/* to the default servlet:
        //    <servlet-mapping>
        //        <servlet-name>default</servlet-name>
        //        <url-pattern>/static/*</url-pattern>
        //    </servlet-mapping>
        //静态资源处理DefaultServlet
        Wrapper defaultServletWrapper=server.addServlet("/", "default", DefaultServlet.class.getTypeName());
        context.addServletMappingDecoded("/static/*", "default");



        //<servlet>
        //    <servlet-name>minisMVC</servlet-name>
        //    <servlet-class>com.minis.web.DispatcherServlet</servlet-class>
        //      <init-param>
        //        <param-name>contextConfigLocation</param-name>
        //        <param-value>/WEB-INF/minisMVC-servlet.xml</param-value>
        //      </init-param>
        //      <load-on-startup>1</load-on-startup>
        //  </servlet>
        //  <servlet-mapping>
        //    <servlet-name>minisMVC</servlet-name>
        //    <url-pattern>/</url-pattern>
        //  </servlet-mapping>
    }

    /**
     * 启动日志
     * @param tomcat
     */
    private static void logAfterStart(Tomcat tomcat){
        int port = tomcat.getConnector().getPort();
        logger.log(Level.INFO," Embed Tomcat Server listen on port : "+ port);
        logger.log(Level.INFO," Embed Tomcat Server Start success.. on port : "+port);
    }


}
